package com.itheima.exception;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.StringJoiner;

@RestControllerAdvice
@Slf4j
public class ProjectExceptionAdvice {

    /**
     * 业务异常
     */
    @ExceptionHandler(BussinessException.class)
    public Result doBusinessException(Exception ex) {
        return Result.error(ex.getMessage());
    }

    /**
     *  后端校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleException(MethodArgumentNotValidException ex) {
        StringJoiner joiner = new StringJoiner(",");
        ex.getBindingResult().getFieldErrors().forEach(e -> {
            joiner.add(e.getDefaultMessage());
        });
        return Result.error(joiner.toString());
    }

    /**
     *  系统异常
     */
    @ExceptionHandler(SystemException.class)
    public Result doSystemException(Exception ex) {
        log.error("系统异常", ex);
        return Result.error("系统出了点问题,请联系管理员");
    }

    /**
     *  程序未知异常
     */
    @ExceptionHandler(Exception.class)
    public Result doException(Exception ex) {
        log.error("未知异常", ex);
        System.out.println(ex.getClass());
        return Result.error("系统出了点问题,请联系管理员");
    }

}
